package models

import (
	"database/sql/driver"
	"fmt"
	"gitee.com/falling-ts/gower/app"
	"gorm.io/gorm"
	"strconv"
)

type Model struct {
	gorm.Model
}

var (
	db     = app.DB()
	trans  = app.Translate()
	auth   = app.Auth()
	util   = app.Util()
	passwd = app.Passwd()
)

func migrate(args ...any) {
	if err := db.AutoMigrate(args...); err != nil {
		panic(err)
	}
}

// IDString 获取 ID 字符串
func (m *Model) IDString() string {
	return strconv.FormatUint(uint64(m.ID), 10)
}

// Bit 自定义 Bit 类型
type bit bool

// Value 实现 driver.Valuer 接口，用于将自定义类型转为数据库值
func (b *bit) Value() (driver.Value, error) {
	if *b {
		return int64(1), nil
	}
	return int64(0), nil
}

// Scan 实现 sql.Scanner 接口，用于将数据库值转为自定义类型
func (b *bit) Scan(value interface{}) error {
	switch v := value.(type) {
	case []byte:
		*b = bit(len(v) > 0 && v[0] != 0)
	case int64:
		*b = bit(v != 0)
	default:
		return fmt.Errorf("cannot scan type %T into BitType", value)
	}
	return nil
}
